<template>
  <div class="app-container">
    <div class="rescue-layout">
      <!-- 左侧：模板列表 -->
      <div class="panel panel--templates">
        <div class="panel-header">
          <i class="el-icon-folder-opened filter-icon"></i>
          <span class="panel-title">模板列表</span>
        </div>
        <el-scrollbar class="template-scroll">
          <div
            v-for="t in templateList"
            :key="t.id"
            class="template-item"
            :class="{ active: templateId === t.id }"
            @click="selectTemplate(t)"
          >
            <div class="template-item__title">{{ t.title }}</div>
            <div class="template-item__sub">{{ t.source }}</div>
          </div>
          <div v-if="!templateList || templateList.length === 0" class="empty-tip">暂无模板</div>
        </el-scrollbar>
      </div>

      <!-- 中间：流程列表 -->
      <div class="panel panel--processes">
        <div class="panel-header">
          <i class="el-icon-connection filter-icon"></i>
          <span class="panel-title">流程</span>
        </div>
        <div v-if="!templateId" class="empty-tip">请先选择左侧模板</div>
        <div v-else class="process-list">
          <div
            v-for="p in processList"
            :key="p.dictValue"
            class="process-item"
            :class="{ active: info && info.dictValue === p.dictValue }"
            @click="selectProcess(p)"
          >
            <div class="process-item__name">{{ p.dictLabel }}</div>
            <el-button
              size="mini"
              type="primary"
              @click.stop="openEditor(p)"
              v-hasPermi="['api:rescue:edit']"
            >配置</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗：流程配置 -->
    <el-dialog
      :title="title || '编辑救援照片配置'"
      :visible.sync="open"
      width="85%"
      append-to-body
    >
      <div class="operation-container">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['api:rescue:add']"
        >新增</el-button>
      </div>

      <el-table
        :data="rescueList"
        border
        class="rescue-table"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" align="center" prop="id" />
        <el-table-column label="流程" align="center" prop="process">
          <template slot-scope="scope">{{ getProcess(scope.row.processNodeCode) }}</template>
        </el-table-column>
        <el-table-column label="模板照片" align="center" prop="img">
          <template slot-scope="scope">
            <image-upload :limit="1" v-model="scope.row.img" />
          </template>
        </el-table-column>
        <el-table-column label="环节名称" align="center" prop="title">
          <template slot-scope="scope">
            <el-input v-model="scope.row.title" size="small" placeholder="请输入环节名称"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="是否必拍" align="center" prop="img">
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.required" size="small">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="title">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.orderNum" size="small" :min="1" :max="10"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row, scope.$index)"
              v-hasPermi="['api:rescue:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRescue, delRescue, addByList, getDicts } from "../../../api/api/rescue";
import { listTemplate } from "@/api/api/template";
export default {
  name: "Rescue",
  data() {
    return {
      templateId: "",
      info: {},
      dataList: [
        { name: "验车", value: "6" },
        { name: "救援过程", value: "7" },
        { name: "牵引上板", value: "8" },
        { name: "辅助轮与装车完毕", value: "9" },
        { name: "目的地卸车报数收款生成工单", value: "10" },
      ],
      processList: [
        // { name: "验车", value: "6" },
        // { name: "装车", value: "1" },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 救援照片默认配置表格数据
      rescueList: [],
      // 弹窗控制
      open: false,
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        img: null,
        title: null,
        required: null,
        orderNum: null,
        process: null,
      },
      templateList: [],
    };
  },
  created() {
    this.temGetList();
    //获取字典数据
    getDicts("data_required_node").then((response) => {
      this.processList = response.data;
    });
  },
  methods: {
    /**
     * 获取模板列表
     * @returns {void}
     */
    temGetList() {
      listTemplate().then((response) => {
        this.templateList = response.rows;
        if (this.templateList && this.templateList.length > 0 && !this.templateId) {
          this.templateId = this.templateList[0].id;
        }
      });
    },
    /**
     * 查询救援照片默认配置列表
     * @param {Object} [processParam] 可选，流程字典项
     * @returns {void}
     */
    getList(processParam) {
      const current = processParam || this.info;
      if (!this.templateId || !current || !current.dictValue) return;
      this.queryParams.processNodeCode = current.dictValue;
      this.queryParams.templateId = this.templateId;
      listRescue(this.queryParams).then((response) => {
        // 确保每条数据绑定当前模板与流程，避免跨模板串联
        this.rescueList = (response.rows || []).map((row) => ({
          ...row,
          templateId: this.templateId,
          processNodeCode: current.dictValue,
        }));
        this.total = response.total;
      });
    },
    /**
     * 选择模板
     * @param {Object} tmpl 模板对象
     * @returns {void}
     */
    selectTemplate(tmpl) {
      this.templateId = tmpl.id;
      this.info = {};
      this.rescueList = [];
      this.open = false;
    },
    /**
     * 选择流程并载入配置
     * @param {Object} row 流程字典项
     * @returns {void}
     */
    selectProcess(row) {
      if (!this.templateId) {
        this.$message.error("请先选择模板！");
        return;
      }
      this.info = row;
      this.getList(row);
    },
    /**
     * 打开流程配置弹窗
     * @param {Object} row 流程字典项
     * @returns {void}
     */
    openEditor(row) {
      if (!this.templateId) {
        this.$message.error("请先选择模板！");
        return;
      }
      this.info = row;
      this.title = `配置 - ${row.dictLabel || ''}`;
      this.getList(row);
      this.open = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.rescueList.push({
        id: "",
        img: "",
        title: "",
        process: this.info.value,
        orderNum: 0,
        templateId: this.templateId,
        processNodeCode: this.info.dictValue,
      });
      console.log(this.rescueList, "this.rescueList");
    },

    getProcess(val) {
      console.log(val, "val");

      let data = {
        checkVehicle: "验车",
        onSiteRescue: "救援过程",
        arriveDestination: "到达目的地",
        completePayment: "费用补齐环节",
        unloadVehicle: "卸车环节",
      };

      console.log(data[val], "data[val]");

      return data[val];
    },
    /** 提交按钮 */
    submitForm() {
      // 提交前强制写入当前模板与流程，避免后端误归属
      const payloadList = (this.rescueList || []).map((item) => ({
        ...item,
        templateId: this.templateId,
        processNodeCode: this.info && this.info.dictValue ? this.info.dictValue : item.processNodeCode,
        required: typeof item.required === 'number' ? item.required : (item.required ? 1 : 0),
      }));
      let params = { rescueImgTypeList: payloadList };
      addByList(params).then((response) => {
        this.$modal.msgSuccess("修改成功");
      });
    },
    /**
     * 关闭弹窗
     * @returns {void}
     */
    cancel() {
      this.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(row, index) {
      if (row.id) {
        const ids = row.id || this.ids;
        this.$modal
          .confirm('是否确认删除救援照片默认配置编号为"' + ids + '"的数据项？')
          .then(function () {
            return delRescue(ids);
          })
          .then(() => {
            this.getList(this.info);
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      } else {
        this.rescueList.splice(index, 1);
        this.$modal.msgSuccess("删除成功");
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "api/rescue/export",
        {
          ...this.queryParams,
        },
        `rescue_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;
}
.filter-icon {
  font-size: 22px;
  color: #4f46e5;
  margin-right: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.rescue-layout {
  display: grid;
  grid-template-columns: 360px 1fr;
  grid-gap: 16px;
  min-height: calc(100vh - 140px);
}

.panel {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 12px 12px 16px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  align-items: center;
  padding-bottom: 12px;
  margin-bottom: 12px;
  border-bottom: 1px solid #f1f5f9;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.template-scroll {
  height: calc(100% - 40px);
}

.template-item {
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all .2s ease;
}
.template-item:hover {
  border-color: #c7d2fe;
  background: #f8fafc;
}
.template-item.active {
  border-color: #6366f1;
  background: #eef2ff;
}
.template-item__title { font-weight: 600; color: #111827; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.template-item__sub { font-size: 12px; color: #6b7280; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

@media (max-width: 1366px) {
  .rescue-layout { grid-template-columns: 320px 1fr; }
}
@media (max-width: 1200px) {
  .rescue-layout { grid-template-columns: 280px 1fr; }
}

.process-list {
  display: grid;
  grid-template-columns: 1fr;
  grid-gap: 10px;
}
.process-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border: 1px dashed #e5e7eb;
  border-radius: 10px;
  cursor: pointer;
}
.process-item.active { border-color: #6366f1; background: #eef2ff; }
.process-item__name { font-weight: 500; color: #1f2937; }

.empty-tip {
  color: #94a3b8;
  font-size: 13px;
  text-align: center;
  padding: 16px 0;
}

.operation-container {
  margin-bottom: 15px;
}

.el-input-number {
  width: 100px;
}

.editor-footer {
  text-align: right;
  margin-top: 10px;
}

/* 弹窗样式与主页面风格统一 */
::v-deep .el-dialog {
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}
::v-deep .el-dialog__header {
  padding: 14px 16px;
  border-bottom: 1px solid #f1f5f9;
}
::v-deep .el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}
::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #6b7280;
}
::v-deep .el-dialog__body {
  padding: 12px 16px 8px;
  background: #ffffff;
  max-height: 65vh;
  overflow: auto;
}
::v-deep .el-dialog__footer {
  padding: 12px 16px;
  border-top: 1px solid #f1f5f9;
}

/* 表格与分页风格统一 */
::v-deep .el-table {
  border-radius: 10px;
  overflow: hidden;
}
::v-deep .el-table th {
  background-color: #f8fafc;
  color: #374151;
}
::v-deep .pagination-container {
  padding: 8px 0 0;
}

/* 紧凑行样式（仅限弹窗表格） */
.rescue-table ::v-deep .el-table__row {
  height: 38px;
}
.rescue-table ::v-deep .cell {
  padding-top: 6px;
  padding-bottom: 6px;
}
</style>
